import wepy from 'wepy'

export default class extends wepy.mixin {
  data = {
    query: '',
    cid: '',
    pagenum: 1,
    pagesize: 10,
    goodsList: [],
    total: 0,
    // 控制触底加载的节流阀
    flag: true,
    isAllLoad: false
  }

  config = {
  }

  methods = {
    goGoodsDetail(goodsId) {
      wepy.navigateTo({
        url: `/pages/goods_detail/main?goods_id=${goodsId}`
      })
    }
  }

  async getGoodsList(cb) {
    if (!this.flag) return
    this.flag = false
    const { data: res } = await wepy.get('/goods/search', {
      query: this.query,
      cid: this.cid,
      pagenum: this.pagenum,
      pagesize: this.pagesize
    })
    console.log(res);
    wepy.baseToast(res)
    this.goodsList = [...this.goodsList, ...res.message.goods]
    this.total = res.message.total
    this.flag = true
    this.$apply()
    cb && cb()
  }
  onLoad(options) {
    this.query = options.query || ''
    this.cid = options.cid || ''
    this.getGoodsList()
  }
  onReachBottom() {
    if (this.pagenum * this.pagesize >= this.total) {
      return this.isAllLoad = true
    } else {
      this.isAllLoad = false
    }
    this.pagenum++
    this.getGoodsList()
  }
  onPullDownRefresh() {
    this.pagenum = 1
    this.pagesize = 10
    this.goodsList = []
    this.total = 0
    this.isAllLoad = false
    this.getGoodsList(() => wepy.stopPullDownRefresh())
  }
}
